package com.github.niefy.common.utils;

import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

/**
 * ehcache缓存操作工具类
 *
 */
@Slf4j
public final class EhCacheUtils {
    /** CacheManager */
    private static final CacheManager CACHE_MANAGER = SpringUtil.getBean(CacheManager.class);

    /**
     * 获取Cache
     */
    public static Cache getCache(String cacheName) {
        return CACHE_MANAGER.getCache(cacheName);
    }

    /**
     * 添加缓存数据
     *
     * @param key   键
     * @param value 值
     * @return 执行结果
     */
    public static boolean put(String key, Object value, String cacheName) {
        try {
            Cache cache = getCache(cacheName);
            cache.put(key, value);
            return true;
        } catch (Exception e) {
            log.error("添加缓存失败：{}", e.getMessage());
            return false;
        }
    }

    /**
     * 获取缓存数据
     *
     * @param key 键
     * @return 缓存数据
     */
    public static <T>T get(String key, String cacheName) {
        try {
            Cache cache = getCache(cacheName);
            return (T) cache.get(key).get();
        } catch (Exception e) {
            log.info("获取缓存数据失败：", e);
            return null;
        }
    }

    /**
     * 删除缓存数据
     *
     * @param key 键
     * @return 执行结果
     */
    public static boolean delete(String key, String cacheName) {
        try {
            Cache cache = getCache(cacheName);
            cache.evict(key);
            return true;
        } catch (Exception e) {
            log.error("删除缓存数据失败：", e);
            return false;
        }
    }

    /**
     * 添加变长存活时间元素
     * @param key
     * @param value
     * @param timeToLiveSeconds 存活时间
     * @return
     */
    public static boolean putIndefLiveTimeElement(final String key, final Object value,
                                        final int timeToLiveSeconds) {
        try {
            Element element = new Element(key, value, 0, timeToLiveSeconds);
            var indefLiveTimeCache = (Ehcache) getCache("indefiniteLiveTimeCache").getNativeCache();
            indefLiveTimeCache.put(element);
            return true;
        } catch (Exception e) {
            log.error("添加缓存失败：{}", e.getMessage());
            return false;
        }
    }

    /**
     * 越过springcache获取原始缓存数据
     *
     * @param key 键
     * @return 缓存数据元素
     */
    public static Element getNativeElement(String key, String cacheName) {
        try {
            Cache cache = getCache(cacheName);
            var nativeCache = (Ehcache) cache.getNativeCache();
            return nativeCache.get(key);
        } catch (Exception e) {
            log.error("获取缓存数据失败：", e);
            return null;
        }
    }

    private EhCacheUtils() {
    }
}
